<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>证书管理</span>
      </div>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="证书编号" prop="certificateNo">
          <el-input
            v-model="queryParams.certificateNo"
            placeholder="请输入证书编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select v-model="queryParams.productId" placeholder="请选择产品" clearable>
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="批次" prop="batchId">
          <el-select v-model="queryParams.batchId" placeholder="请选择批次" clearable>
            <el-option
              v-for="item in batchOptions"
              :key="item.id"
              :label="item.batchNo"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="certificateStatus">
          <el-select v-model="queryParams.certificateStatus" placeholder="请选择状态" clearable>
            <el-option label="已签发" value="已签发" />
            <el-option label="已作废" value="已作废" />
            <el-option label="草稿" value="草稿" />
          </el-select>
        </el-form-item>
        <el-form-item label="签发日期" prop="issueDateRange">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleGenerate"
            v-hasPermi="['certificate:manage:generate']"
          >生成证书</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['certificate:manage:export']"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['certificate:manage:remove']"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="certificateList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="证书编号" align="center" prop="certificateNo" />
        <el-table-column label="模板" align="center" prop="templateName" :show-overflow-tooltip="true" />
        <el-table-column label="产品" align="center" prop="productName" :show-overflow-tooltip="true" />
        <el-table-column label="批次" align="center" prop="batchNo" />
        <el-table-column label="签发日期" align="center" prop="issueDate" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.issueDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="签发人" align="center" prop="issuer" />
        <el-table-column label="状态" align="center" prop="certificateStatus">
          <template slot-scope="scope">
            <el-tag :type="scope.row.certificateStatus === '已签发' ? 'success' : (scope.row.certificateStatus === '已作废' ? 'danger' : 'info')">
              {{ scope.row.certificateStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              link
              icon="el-icon-view"
              @click="handlePreview(scope.row)"
              v-hasPermi="['certificate:manage:query']"
            >预览</el-button>
            <el-button
              size="mini"
              link
              icon="el-icon-printer"
              @click="handlePrint(scope.row)"
              v-hasPermi="['certificate:manage:query']"
            >打印</el-button>
            <el-button
              size="mini"
              link
              icon="el-icon-edit"
              @click="handleChangeStatus(scope.row)"
              v-if="scope.row.certificateStatus !== '已作废'"
              v-hasPermi="['certificate:manage:edit']"
            >状态</el-button>
            <el-button
              size="mini"
              link
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['certificate:manage:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 预览证书对话框 -->
      <el-dialog title="预览证书" :visible.sync="previewOpen" width="800px" append-to-body>
        <div v-html="previewContent" class="certificate-preview"></div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="previewOpen = false">关 闭</el-button>
          <el-button type="primary" @click="printPreview">打 印</el-button>
        </div>
      </el-dialog>

      <!-- 修改状态对话框 -->
      <el-dialog title="修改证书状态" :visible.sync="statusDialogVisible" width="500px" append-to-body>
        <el-form ref="statusForm" :model="statusForm" label-width="80px">
          <el-form-item label="证书编号">
            <span>{{ statusForm.certificateNo }}</span>
          </el-form-item>
          <el-form-item label="当前状态">
            <el-tag :type="statusForm.certificateStatus === '已签发' ? 'success' : (statusForm.certificateStatus === '已作废' ? 'danger' : 'info')">
              {{ statusForm.certificateStatus }}
            </el-tag>
          </el-form-item>
          <el-form-item label="新状态" prop="newStatus">
            <el-select v-model="statusForm.newStatus" placeholder="请选择新状态">
              <el-option label="已签发" value="已签发" />
              <el-option label="已作废" value="已作废" />
              <el-option label="草稿" value="草稿" />
            </el-select>
          </el-form-item>
          <el-form-item label="原因" prop="reason" v-if="statusForm.newStatus === '已作废'">
            <el-input v-model="statusForm.reason" type="textarea" placeholder="请输入作废原因"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmChangeStatus">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { listCertificate, getCertificate, delCertificate, updateCertificateStatus, previewCertificate, printCertificate, exportCertificate } from "@/api/certificate/manage";
import { listProduct } from "@/api/qep/product";
import { listBatch } from "@/api/qep/batch";

export default {
  name: "CertificateManage",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 证书表格数据
      certificateList: [],
      // 日期范围
      dateRange: [],
      // 产品选项
      productOptions: [],
      // 批次选项
      batchOptions: [],
      // 预览窗口
      previewOpen: false,
      // 预览内容
      previewContent: "",
      // 状态修改对话框
      statusDialogVisible: false,
      // 状态表单
      statusForm: {
        id: null,
        certificateNo: "",
        certificateStatus: "",
        newStatus: "",
        reason: ""
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        certificateNo: null,
        productId: null,
        batchId: null,
        certificateStatus: null,
        beginIssueDate: null,
        endIssueDate: null
      }
    };
  },
  created() {
    this.getList();
    this.getProductOptions();
  },
  methods: {
    /** 查询证书列表 */
    getList() {
      this.loading = true;
      
      // 处理日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.beginIssueDate = this.dateRange[0];
        this.queryParams.endIssueDate = this.dateRange[1];
      } else {
        this.queryParams.beginIssueDate = null;
        this.queryParams.endIssueDate = null;
      }
      
      listCertificate(this.queryParams).then(response => {
        this.certificateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取产品选项 */
    getProductOptions() {
      listProduct({ pageSize: 100 }).then(response => {
        this.productOptions = response.rows || [];
      });
    },
    /** 获取批次选项 */
    getBatchOptions(productId) {
      if (productId) {
        listBatch({ productId: productId, pageSize: 100 }).then(response => {
          this.batchOptions = response.rows || [];
        });
      } else {
        this.batchOptions = [];
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 生成证书按钮操作 */
    handleGenerate() {
      this.$router.push('/certificate/manage/generate');
    },
    /** 预览按钮操作 */
    handlePreview(row) {
      previewCertificate(row.id).then(response => {
        this.previewContent = response.data;
        this.previewOpen = true;
      });
    },
    /** 打印预览内容 */
    printPreview() {
      const printWindow = window.open('', '_blank');
      printWindow.document.write(`
        <html>
          <head>
            <title>证书打印</title>
            <style>
              body { font-family: Arial, sans-serif; }
              @media print {
                body { margin: 0; padding: 0; }
              }
            </style>
          </head>
          <body>
            ${this.previewContent}
            <script>
              window.onload = function() {
                window.print();
                setTimeout(function() { window.close(); }, 500);
              };
            </script>
          </body>
        </html>
      `);
      printWindow.document.close();
    },
    /** 打印按钮操作 */
    handlePrint(row) {
      printCertificate(row.id).then(response => {
        // 创建打印窗口
        const printContent = response.data;
        const printWindow = window.open('', '_blank');
        printWindow.document.write(`
          <html>
            <head>
              <title>证书打印</title>
              <style>
                body { font-family: Arial, sans-serif; }
                @media print {
                  body { margin: 0; padding: 0; }
                }
              </style>
            </head>
            <body>
              ${printContent}
              <script>
                window.onload = function() {
                  window.print();
                  setTimeout(function() { window.close(); }, 500);
                };
              </script>
            </body>
          </html>
        `);
        printWindow.document.close();
      });
    },
    /** 修改状态按钮操作 */
    handleChangeStatus(row) {
      this.statusForm = {
        id: row.id,
        certificateNo: row.certificateNo,
        certificateStatus: row.certificateStatus,
        newStatus: "",
        reason: ""
      };
      this.statusDialogVisible = true;
    },
    /** 确认修改状态 */
    confirmChangeStatus() {
      if (!this.statusForm.newStatus) {
        this.$message.warning('请选择新状态');
        return;
      }
      
      if (this.statusForm.newStatus === '已作废' && !this.statusForm.reason) {
        this.$message.warning('请输入作废原因');
        return;
      }
      
      updateCertificateStatus(this.statusForm.id, this.statusForm.newStatus).then(() => {
        this.$message.success('状态修改成功');
        this.statusDialogVisible = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除证书编号为"' + ids + '"的数据项？').then(function() {
        return delCertificate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('certificate/manage/export', {
        ...this.queryParams
      }, `certificate_${new Date().getTime()}.xlsx`)
    }
  },
  watch: {
    'queryParams.productId': {
      handler(val) {
        this.queryParams.batchId = null;
        this.getBatchOptions(val);
      }
    }
  }
};
</script>

<style scoped>
.certificate-preview {
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 400px;
  max-height: 600px;
  overflow-y: auto;
}
</style> 